/*
* 领料单列表
* */
import 'dart:convert';

import 'package:center_beijing/api/material_science_api.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/pull_select_widget.dart';
import 'package:center_beijing/widgets/search_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

class MaterialRequisitionList extends StatefulWidget {
  @override
  _MaterialRequisitionListState createState() =>
      _MaterialRequisitionListState();
}

class _MaterialRequisitionListState extends State<MaterialRequisitionList>
    with SingleTickerProviderStateMixin {
  EasyRefreshController _controller = EasyRefreshController();
  CustomLoading loading = CustomLoading.withMessage('提交中...');
  var receive = Get.arguments;
  List dataSource = [];
  int page = 1;
  int pageSize = 15;
  bool firstLoad = true;
  List<SelectItems> typeList = [SelectItems(label: '全部类型', value: ''),SelectItems(label: '出库', value: '1'),SelectItems(label: '退库', value: '2'),SelectItems(label: '调拨', value: '3')];
  SelectItems selectType = SelectItems(label: '全部类型', value: '');
  TextEditingController _textInput = TextEditingController();
  List<SelectItems> factoriesList = [SelectItems(label: '全部仓库', value: '-1')];
  SelectItems selectFactory = SelectItems(label: '全部仓库', value: '-1');
  @override
  void initState() {
    super.initState();
    bus.on('refreshRequisitionList', (arg) {
      if (mounted) {
        _controller.callRefresh();
      }
    });
    this.getWarehouse();
  }

  /*
  * 获取仓库
  * */
  getWarehouse() async {
    var result =
    await getInWarehouse({'projectSectionId': GlobalConfig.selectFactory.tag,'houseType':'1'});
    if (result != null) {
      List<SelectItems> tem = [SelectItems(label: '全部仓库', value: '-1')];
      result.forEach((item) {
        tem.add(SelectItems(
            label: item['houseName'], value: item['id'].toString(), dict: item));
      });
      this.setState(() {
        factoriesList = tem;
      });
    }
    LogUtil.d(result);
  }

  /*
  * 获取领料单列表
  * */
  getAllReceived() async {
    var pass = {
      'queryFields': json.encode([
        {
          "columnName": 'projectSectionId',
          "dataType": "string",
          "operator": "=",
          "queryValue": GlobalConfig.selectFactory.tag
        },
        {
          "columnName": "docNumber",
          "dataType": "string",
          "operator": "like",
          "queryValue": _textInput.text
        },
        {
          "columnName": "requestType",
          "dataType": "string",
          "operator": "=",
          "queryValue": selectType.value
        }
      ]),
      'page': page,
      'limit': pageSize,
    };
    var result = await getReceivedExList(pass);
    loading.dismiss();
    if (this.page == 1) {
      dataSource.clear();
    }
    firstLoad = false;
    if (result != null && result['hasError'] == null) {
      this.setState(() {
        if (result['results'].length == 0) {
          _controller.finishLoad(success: true, noMore: true);
        } else {
          dataSource.addAll(result['results']);
          if (dataSource.length == result['totalRecordNum']) {
            _controller.finishLoad(success: true, noMore: true);
          }
        }
      });
    } else {
      _controller.finishLoad(success: true);
    }
  }

  /*
  * 发起审批
  * */
  sendAccept(value) async {
    loading.show(delay: 30);
    var result = await saveSubmitAccept({'requisitionAcceptId': value['id']});
    loading.dismiss();
    if (result != null&& result['hasError'] == null) {
      Fluttertoast.showToast(msg: '发起成功');
      page = 1;
      this.getAllReceived();
      bus.emit('refreshHome');
    }
    LogUtil.d(result);
  }

  /*
  * 删除领料单
  * */
  deleteMaterial(value) async {
    loading.show(delay: 30);
    var result = value
    ['isAcceptItem'] ==
        '1'
        ? await deleteMaterialOne({'id': value['id']})
        : await deleteMaterialTwo({'id': value['id']});
    loading.dismiss();
    if (result != null&& result['hasError'] == null) {
      Fluttertoast.showToast(msg: '删除成功');
      // page = 1;
      // this.getAllReceived();
      this.setState(() {
        this.dataSource.remove(value);
      });
    }
    LogUtil.d(result);
  }

  @override
  void dispose() {
    _controller.dispose();
    bus.off('refreshRequisitionList');
    super.dispose();
  }

  getStatus(value){
    if(value['materialLevel']=='1'){
return '';
    }else{
      if(value['recordEditFlag']==1){
return '审核通过';
      }else if(value['recordEditFlag']==3){
        return '审核不通过';
      }else{
        if(value['wfProcInstId']!=null){
          return '审核中';
        }else {
          return '';
        }
      }
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('领料单'),
        ),
        body: Container(
          color: Styles.MainBackgroundColor,
          padding: EdgeInsets.fromLTRB(
              0, 0, 0, MediaQuery.of(context).padding.bottom + 70),
          child:  Column(
            children: [
              Container(
                margin: EdgeInsets.fromLTRB(Styles.spacing16,
                    Styles.spacing8, Styles.spacing16, Styles.spacing8),
                child: SearchWidget(
                  textInput: _textInput,
                  placeholder: '请输入单号',
                  textSubmit: (value) {
                    page = 1;
                    // _controller.finishLoad(success: true, noMore: false);
                    this.getAllReceived();
                  },
                ),
              ),
              Container(
                color: Colors.white,
                padding: EdgeInsets.fromLTRB(Styles.spacing16, Styles.spacing4,
                    Styles.spacing16, Styles.spacing4),
                child: Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: Container(
                        color: Colors.white,
                        child: PullSelectWidget(
                          text_align: TextAlign.center,
                          rightText: selectFactory.label,
                          backColor: Colors.white,
                          items: factoriesList,
                          selectCallback: (value) {
                            this.selectFactory = value;
                            page = 1;
                            loading.show(delay: 15);
                            this.getAllReceived();
                          },
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child: Container(
                        color: Colors.white,
                        child: PullSelectWidget(
                          text_align: TextAlign.center,
                          rightText: selectType.label,
                          backColor: Colors.white,
                          items: typeList,
                          selectCallback: (value) {
                            this.selectType = value;
                            page = 1;
                            loading.show(delay: 15);
                            this.getAllReceived();
                          },
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(child: EasyRefresh.custom(
                  shrinkWrap: true,
                  firstRefresh: true,
                  controller: _controller,
                  header: MaterialHeader(),
                  footer: ClassicalFooter(
                      loadingText: '加载中',
                      loadText: '上拉加载',
                      noMoreText: '没有更多数据',
                      loadedText: '加载完成',
                      infoText: '更新于 %T',
                      textColor: Styles.NoMoreColor,
                      showInfo: false),
                  emptyWidget: (dataSource.length == 0 && !firstLoad)
                      ? Center(
                    child: Image(
                      image: AssetImage('assets/images/no_data.png'),
                      width: 128,
                      height: 150,
                    ),
                  )
                      : null,
                  onRefresh: () async {
                    _controller.finishLoad(success: true, noMore: false);
                    if (mounted) {
                      page = 1;
                      this.getAllReceived();
                    }
                  },
                  onLoad: () async {
                    await Future.delayed(Duration(seconds: 2), () {
                      if (mounted) {
                        page++;
                        this.getAllReceived();
                      }
                    });
                  },
                  slivers: <Widget>[
                    SliverList(
                      delegate: SliverChildBuilderDelegate(
                            (context, index) {
                          return GestureDetector(
                            onTap: () {
                              var type = (this.dataSource[index]
                              ['isAcceptItem'] ==
                                  '1' &&
                                  this.dataSource[index]['recordEditFlag'] != 2 &&
                                  this.dataSource[index]['recordEditFlag'] != 3 &&
                                  this.dataSource[index]['wfProcInstId'] == null);
                              if(this.dataSource[index]['materialLevel']=='1'){
                                Get.toNamed(
                                    RouteConfig.materialRequisitionDetailList,
                                    arguments: {
                                      'pass': this.dataSource[index],
                                      'type': type,
                                      'canEdit':true
                                    });
                              }else{
                                Get.toNamed(
                                    RouteConfig.materialRequisitionDetailList,
                                    arguments: {
                                      'pass': this.dataSource[index],
                                      'type': (this.dataSource[index]['recordEditFlag']!=1&&this.dataSource[index]['recordEditFlag']!=3&&this.dataSource[index]['wfProcInstId']==null)?type:true,
                                      'canEdit':(this.dataSource[index]['recordEditFlag']!=1&&this.dataSource[index]['recordEditFlag']!=3&&this.dataSource[index]['wfProcInstId']==null)
                                    });
                              }

                            },
                            child: Container(
                              color: Colors.white,
                              margin:
                              EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                              padding: EdgeInsets.fromLTRB(
                                  Styles.spacing12,
                                  Styles.spacing8,
                                  Styles.spacing12,
                                  Styles.spacing8),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0, Styles.spacing4, 0, Styles.spacing4),
                                    child: Text(
                                      '单据编号  ${this.dataSource[index]['docNumber']}',
                                      style: TextStyle(
                                          color: Styles.DetailColor,
                                          fontSize: Styles.NormalFont),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0, Styles.spacing4, 0, Styles.spacing4),
                                    child: Text(
                                      '领用时间  ${this.dataSource[index]['requestDateStr']}',
                                      style: TextStyle(
                                          color: Styles.DetailColor,
                                          fontSize: Styles.NormalFont),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0, Styles.spacing4, 0, Styles.spacing4),
                                    child: Text(
                                      '领用类型  ${this.dataSource[index]['requestTypeCaption']}',
                                      style: TextStyle(
                                          color: Styles.DetailColor,
                                          fontSize: Styles.NormalFont),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0, Styles.spacing4, 0, Styles.spacing4),
                                    child: Text(
                                      '发料仓库  ${this.dataSource[index]['outHouseName']}',
                                      style: TextStyle(
                                          color: Styles.DetailColor,
                                          fontSize: Styles.NormalFont),
                                    ),
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Container(
                                        margin: EdgeInsets.fromLTRB(
                                            0, Styles.spacing4, 0, Styles.spacing4),
                                        child: Text(
                                          '发  料  人  ${this.dataSource[index]['distributor']}',
                                          style: TextStyle(
                                              color: Styles.DetailColor,
                                              fontSize: Styles.NormalFont),
                                        ),
                                      ),
                                      Container(
                                        margin: EdgeInsets.fromLTRB(
                                            0, Styles.spacing4, 0, Styles.spacing4),
                                        child: Text(
                                          this.getStatus(this.dataSource[index]),
                                          style: TextStyle(
                                              color: Styles.DetailColor,
                                              fontSize: Styles.NormalFont),
                                        ),
                                      ),
                                    ],
                                  ),
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0, Styles.spacing4, 0, Styles.spacing4),
                                    child: Text(
                                      '领料仓库  ${this.dataSource[index]['requestHouseName']}',
                                      style: TextStyle(
                                          color: Styles.DetailColor,
                                          fontSize: Styles.NormalFont),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0, Styles.spacing4, 0, Styles.spacing4),
                                    child: Text(
                                      '领  料  人  ${this.dataSource[index]['requestor']}',
                                      style: TextStyle(
                                          color: Styles.DetailColor,
                                          fontSize: Styles.NormalFont),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0, Styles.spacing4, 0, Styles.spacing4),
                                    child: Text(
                                      '材料量级  ${this.dataSource[index]['materialLevelCaption']}',
                                      style: TextStyle(
                                          color: Styles.DetailColor,
                                          fontSize: Styles.NormalFont),
                                    ),
                                  ),
                                  Row(
                                    children: [
                                      (this.dataSource[index]['materialLevel']=='1'||(this.dataSource[index]['recordEditFlag']!=1&&this.dataSource[index]['recordEditFlag']!=3))?
                                      Expanded(
                                          child: GestureDetector(
                                            onTap: () {
                                              if(this.dataSource[index]['materialLevel']=='1'||(this.dataSource[index]['recordEditFlag']!=1&&this.dataSource[index]['recordEditFlag']!=3&&(this.dataSource[index]['recordEditFlag']!=1&&this.dataSource[index]['wfProcInstId']==null))){
                                                Get.toNamed(
                                                    RouteConfig.addMaterialRequisition,
                                                    arguments: this.dataSource[index]);
                                              }else{
                                                Fluttertoast.showToast(msg: '领料单审批中，不可修改！');
                                              }

                                            },
                                            child: Container(
                                              padding:
                                              EdgeInsets.all(Styles.spacing8),
                                              margin: EdgeInsets.all(Styles.spacing8),
                                              decoration: BoxDecoration(
                                                  border: Border.all(
                                                      color: Styles.BlueColor,
                                                      width: 1)),
                                              alignment: Alignment.center,
                                              child: Text(
                                                '编辑',
                                                style: TextStyle(
                                                    color: Styles.BlueColor,
                                                    fontSize: Styles.NormalFont),
                                              ),
                                            ),
                                          )):Container(),
                                      Expanded(
                                          child: GestureDetector(
                                            onTap: () {
                                              FocusScope.of(context).requestFocus(new FocusNode());
                                              showDialog(
                                                  barrierDismissible: false,
                                                  context: this.context,
                                                  builder:
                                                      (BuildContext context) {
                                                    return AlertDialog(
                                                      title: Text('注意'),
                                                      content: Text('确认删除吗？'),
                                                      actions: <Widget>[
                                                        new Container(
                                                          child: FlatButton(
                                                            child: new Text(
                                                              "取消",
                                                              style: TextStyle(
                                                                  color: Colors
                                                                      .black),
                                                            ),
                                                            onPressed: () {
                                                              Navigator.pop(
                                                                  context);
                                                            },
                                                          ),
                                                        ),
                                                        new Container(
                                                          child: FlatButton(
                                                            child: new Text(
                                                              "确定",
                                                              style: TextStyle(
                                                                  color: Colors
                                                                      .red),
                                                            ),
                                                            onPressed: () {
                                                              Navigator.pop(
                                                                  context);
                                                              this.deleteMaterial(
                                                                  this.dataSource[index]);
                                                            },
                                                          ),
                                                        ),
                                                      ],
                                                    );
                                                  });

                                            },
                                            child: Container(
                                              padding:
                                              EdgeInsets.all(Styles.spacing8),
                                              margin: EdgeInsets.all(Styles.spacing8),
                                              decoration: BoxDecoration(
                                                  border: Border.all(
                                                      color: Styles.RedColor,
                                                      width: 1)),
                                              alignment: Alignment.center,
                                              child: Text(
                                                '删除',
                                                style: TextStyle(
                                                    color: Styles.RedColor,
                                                    fontSize: Styles.NormalFont),
                                              ),
                                            ),
                                          )),
                                    ],
                                  )
                                ],
                              ),
                            ),
                          );
                        },
                        childCount: dataSource.length,
                      ),
                    ),
                  ]))
            ],
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Container(
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: Container(
            decoration: new BoxDecoration(
              //背景
              color: Styles.BlueColor,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
            ),
            child: FlatButton(
              disabledColor: Styles.SelectColor,
              onPressed: () {
                Get.toNamed(RouteConfig.addMaterialRequisition);
              },
              child: Container(
                height: Styles.MainButtonHeight,
                alignment: Alignment.center,
                child: Text(
                  '新增领料单',
                  style: TextStyle(
                      fontSize: Styles.MainButtonTextFont, color: Colors.white),
                ),
              ),
            ),
          ),
        ));
  }
}
